package optimizers.commons.evaluator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.Callable;

import fitness.Fitness;
import fitness.FitnessResult;
import fitness.MathFitness;
import fitness.MathResult;

import model.OligoSystemGeneral;

public class FitnessEvaluationTask implements Callable<Object> {

	private int index;
	private OligoSystemGeneral oligoSystem;
	private Fitness evaluator;

	public FitnessEvaluationTask(int i, OligoSystemGeneral oligoSystem,
			Fitness evaluator) {
		this.index = i;
		this.oligoSystem = oligoSystem;
		this.evaluator = evaluator;
	}

	@Override
	public Object call() {
		long startTime = System.currentTimeMillis();
		fitness.FitnessResult result = evaluator.minFitness(oligoSystem);
		try {
			String fileIn = "_indiv_" + this.index + "_"+System.currentTimeMillis();
			String fileOut = "_indiv_" + this.index + "_out" + "_"+System.currentTimeMillis();
			FileOutputStream saveFile = new FileOutputStream(fileIn);
			ObjectOutputStream save = new ObjectOutputStream(saveFile);
			save.writeObject(oligoSystem);
			save.close();
			saveFile.close();
			ClusterNode clusterNode = null;
			while (clusterNode == null) {
				clusterNode = ClusterSystem.getFirstFreeNode();
			}
			clusterNode.compute(new String[] { "evaluator", fileIn, fileOut,
					String.valueOf(oligoSystem.nSimpleSequences * 60) });
			FileInputStream readFile;
			readFile = new FileInputStream(fileOut);
			ObjectInputStream restore = new ObjectInputStream(readFile);
			result = (FitnessResult) restore.readObject();
			restore.close();
			readFile.close();
			File file = new File(fileOut);
			file.delete();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		double estimatedTime = ((double) System.currentTimeMillis() - startTime) / 1000;
		return new FitnessEvaluationResult(index, result, estimatedTime);
	}
}
